package com.wang.example.netty.codec.lengthfield;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;


public class LengthFieldEchoServerInHandler extends ChannelInboundHandlerAdapter {
    /**
     * 服务端读取到网络数据后的处理
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)
            throws Exception {
        //ByteBuf为netty实现的缓冲区
        ByteBuf in = (ByteBuf)msg;
        String msgStr = in.toString(CharsetUtil.UTF_8);
        System.out.println("LengthField server receive:" + msgStr);
        //创建一个响应的buf 设置指定的字符串
        ByteBuf resBuf = Unpooled.copiedBuffer(msgStr + System.currentTimeMillis() ,
                CharsetUtil.UTF_8);
        //写回客户端
        ctx.writeAndFlush(resBuf);

    }
}
